package cn.com.agree.service.impl;

import cn.com.agree.common.constant.GloPropertyConstant;
import cn.com.agree.common.util.FileUtil;
import cn.com.agree.common.util.RSAUtil;
import cn.com.agree.dto.book.CreateOrUpdateBookDTO;
import cn.com.agree.dto.book.CreateOrUpdateMackDTO;
import cn.com.agree.mapper.ProductMacMapper;
import cn.com.agree.mapper.ProductMapper;
import cn.com.agree.model.ProductDO;
import cn.com.agree.model.ProductMacDO;
import cn.com.agree.service.ProductService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * @author pedro@TaleLin
 * @author Juzi@TaleLin
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductMacMapper producMactMapper;

    @Override
    public boolean createBook(CreateOrUpdateBookDTO validator) {
        ProductDO product = new ProductDO();
        ProductMacDO productMac = new ProductMacDO();
        product.setAuthor(validator.getAuthor());
        product.setTitle(validator.getTitle());
        product.setSummary(validator.getSummary());
        product.setBcode(validator.getBcode());
        product.setProduct(validator.getProduct());
        product.setImage(validator.getImage());  //现在将所有的物理地址放在image中

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(validator.getCreateTime());
        calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
        Date cdate=calendar.getTime(); //这个时间就是日期往后推一天的结果

        calendar.setTime(validator.getOverTime());
        calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
        Date odate=calendar.getTime(); //这个时间就是日期往后推一天的结果

        product.setCreateTime(cdate);
        product.setOverTime(odate);
        Date date = new Date();
        product.setUpdateTime(new Date());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String now = sdf.format(new Date());
        try {
            long nowtime = sdf.parse(now).getTime();
            long lasttime = validator.getOverTime().getTime();
            if(lasttime >= nowtime){
                product.setPstatus("0");
            }else{
                product.setPstatus("2");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if(validator.getImage().contains("\n")){
            String[] count = validator.getImage().split("\n");
            product.setCount(String.valueOf(count.length));
            productMac.setBcode(validator.getBcode());
            productMac.setMac(validator.getAuthor());
            product.setSummary(validator.getSummary());
            product.setBcode(validator.getBcode());
            for(int i=0;i<count.length;i++){
                productMac.setMark(count[i]);
                producMactMapper.insert(productMac);
            }
        }else if(validator.getImage()!=null && validator.getImage()!=""){
            product.setCount("1");
        }else{
            product.setCount("0");
        }
        return productMapper.insert(product) > 0;
    }

    @Override
    public List<ProductDO> getBookByKeyword(String q) {
        List<ProductDO> books = productMapper.selectByTitleLikeKeyword(q);
        return books;
    }

    @Override
    public boolean updateBook(ProductDO book, CreateOrUpdateBookDTO validator) {
        String bcode = book.getBcode();
        ProductMacDO productMac = new ProductMacDO();
        book.setAuthor(validator.getAuthor());
        book.setTitle(validator.getTitle());
        book.setBcode(validator.getBcode());
        book.setProduct(validator.getProduct());
        book.setPstatus(validator.getPstatus());
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(validator.getOverTime());
        calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
        Date odate=calendar.getTime(); //这个时间就是日期往后推一天的结果
        book.setOverTime(odate);
        book.setUpdateTime(new Date());
//        if(book.getImage() != validator.getImage()){
//            String[] lastCount = validator.getImage().split("\n");
//            String[] newCount = validator.getImage().split("\n");
//            productMac.setBcode(validator.getBcode());
//            productMac.setMac(validator.getAuthor());
//            String[] terr;
//            if(validator.getImage().contains("\n")){
//                book.setCount(String.valueOf(newCount.length));
//            }else if(validator.getImage()!=null && validator.getImage()!=""){
//                book.setCount("1");
//            }else{
//                book.setCount("0");
//            }

//            for(int i=0;i< lastCount.length;i++){
//                //删除原来的所有物理地址
//                producMactMapper.deleteByBcode(bcode);
//            }
//            for(int i=0;i< newCount.length;i++){
//                //添加新的物理地址
//                productMac.setMark(newCount[i]);
//                producMactMapper.insert(productMac);
//            }
//        }
        book.setSummary(validator.getSummary());
        book.setImage(validator.getImage());
        return productMapper.updateById(book) > 0;
    }

    @Override
    public boolean updatePro(ProductDO productDO){
        return productMapper.updateById(productDO) > 0;
    }

    @Override
    public ProductDO getById(Integer id) {
        ProductDO book = productMapper.selectById(id);
        return book;
    }

    @Override
    public List<ProductDO> findAll() {
        List<ProductDO> books = productMapper.selectList(null);
        return books;
    }

    @Override
    public List<ProductDO> SelectProAll() {
        List<ProductDO> books = productMapper.selecProtList();
        return books;
    }

    @Override
    public boolean deleteById(Integer id) {
        return productMapper.deleteById(id) > 0;
    }

    @Override
    public List<ProductMacDO> getMacListByBcode(String bcode) {
        return producMactMapper.selectListByBcode(bcode);
    }

    //查询还有一个月失效的版本的数量
    @Override
    public String[] selectListByOvertimeLess(){
        List<ProductDO> list = productMapper.selectListByOvertimeLess();
        String name = "";
        for (ProductDO pro:list) {
            name += pro.getTitle()+"、";
        }
        String[] data = new String[2];
        data[0] = String.valueOf(list.size());
        data[1] = name;
        return data;
    }

    //查询失效的版本
    @Override
    public Integer selectByOvertimeOver(){
        String p = String.valueOf(2);
        return  productMapper.selectByOvertimeOver(p).size();
    }

    @Override
    public int selectCount(){
        return  productMapper.selectCount();
    }

    @Override
    public boolean updatePstatus(Integer id){
        return productMapper.updatePstatus(id) >0;
    }

    @Override
    public String downloadLic(ProductDO pro) {

        String title = pro.getTitle();
        //当前用户的桌面路径
        String desktopPath = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath();
//      String nowTime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String destFilePath = desktopPath + File.separator + GloPropertyConstant.LICENSE_FILENAME;
        //本地资源父路径
        String  respath = FileUtil.getResourceBasePath()+GloPropertyConstant.LICENSE_FILEPATH;
        // replaceAll 是将 windows 平台下的 \ 替换为 /
        if(System.getProperties().getProperty("os.name").toUpperCase().contains("LINUX")){
            respath=respath.replaceAll("\\\\","/");
        }
        //下载资源
        respath = respath+"/"+pro.getBcode()+"/"+GloPropertyConstant.LICENSE_FILENAME;
        SimpleDateFormat formatter = new SimpleDateFormat(RSAUtil.DateFormat);
        String dateString = formatter.format(pro.getOverTime());

        try{
            List<ProductMacDO> list= producMactMapper.selectListByBcode(pro.getBcode());
            RSAUtil.genLicenseFile(dataready(list),dateString,respath);
            return FileUtil.transformfile(respath);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("文件下载失败！");
        }

        return "";
    }


    private JSONArray dataready(List<ProductMacDO> pmaclist)throws Exception{

        JSONArray jsonarrgens = new JSONArray();
        for (ProductMacDO object : pmaclist) {
            String mark = object.getMark();
            mark=mark.replace(" ", "");
            if(mark.contains("\r")){
                mark=mark.replace("\r", "");
            }
            if(mark.equals("")){
                continue;
            }
            mark=mark.toUpperCase().replaceAll("[\\.:-]", "");
            jsonarrgens.add(mark);

        }
        if(jsonarrgens.size()==0){
            throw  new Exception("物理地址为空！");
        }
        return jsonarrgens;
    }

    @Override
    public List<ProductDO> getAllByMore(ProductDO pro){
        return productMapper.selectByMore(pro);
    }

    @Override
    public boolean deleteMacById(Integer id) {
        return  producMactMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateMac(ProductMacDO product, CreateOrUpdateMackDTO validator){
        product.setMark(validator.getMark());
        return producMactMapper.updateById(product)>0;
    }

    @Override
    public ProductMacDO getByMacId(Integer id) {
        ProductMacDO pro = producMactMapper.selectById(id);
        return pro;
    }

    @Override
    public boolean createMac(CreateOrUpdateMackDTO validator){
        ProductMacDO pro = new ProductMacDO();
        pro.setMark(validator.getMark());
        pro.setMac(validator.getMac());
        pro.setBcode(validator.getBcode());

        return producMactMapper.insert(pro)>0;
    }

    @Override
    public ProductDO selectByBcode(String bcode){
        return productMapper.selectByBcode(bcode);
    }

}
